package com.yaopaikeji.util;

import com.yaopaikeji.constants.Constants;
import com.yaopaikeji.model.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

public class LoginHelper {

    /**
     * 登陆
     * @param user
     */
    public static boolean login(User user){

        if(user == null)
            return false;

        HttpSession httpSession = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        httpSession.setAttribute(Constants.CURRENT_USER,user);

        return true;
    }

    /**
     * 是否已经登陆
     * @return
     */
    public static boolean isLogined(){

        return getCurrentUser() != null;
    }

    /**
     * 是否是管理员
     */
    public static boolean isAdmin(){

        User currentUser = getCurrentUser();

        if(currentUser == null)
            return false;

        return Constants.ROLE_ADMIN_NAME.equals(currentUser.getRoleInfo().getRoleName());
    }

    /**
     * 是否是超级用户
     */
    public static boolean isRoot(){

        User currentUser = getCurrentUser();

        if(currentUser == null)
            return false;

        return Constants.ROLE_ROOT_NAME.equals(currentUser.getRoleInfo().getRoleName());

    }

    /**
     * 清除登陆信息
     */
    public static void removeLoginInfo(){

        HttpSession httpSession = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        User currentUser = (User) httpSession.getAttribute(Constants.CURRENT_USER);

        if(currentUser != null){
            httpSession.removeAttribute(Constants.CURRENT_USER);
        }
    }

    /**
     *获取当前登陆信息
     */

    public static User getCurrentUser(){

        HttpSession httpSession = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        return  (User) httpSession.getAttribute(Constants.CURRENT_USER);
    }

    /**
     * 更新当前登陆信息
     */

    public static void updateCurrentUser(User user){

        HttpSession httpSession = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        httpSession.setAttribute(Constants.CURRENT_USER,user);
        return;
    }
}
